package com.weir.resources.permissions.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weir.resources.permissions.entity.PermMenu;
import com.weir.resources.permissions.entity.PermUser;
import com.weir.resources.permissions.mapper.PermMenuMapper;
import com.weir.resources.permissions.mapper.PermUserMapper;

@Component
public class WeirUserDetailsService implements UserDetailsService {

	@Autowired
	private PermUserMapper permUserMapper;
	@Autowired
	private PermMenuMapper permMenuMapper;

	// 查询用户信息
	@Override
	public User loadUserByUsername(String username) throws UsernameNotFoundException {
		PermUser permUser = permUserMapper.selectOne(new QueryWrapper<PermUser>().eq("username", username.trim()));
		if (permUser == null) {
			return null;
		}

		List<GrantedAuthority> authorities = new ArrayList<>();
		List<PermMenu> permMenus = permMenuMapper.selectByUserId(permUser.getId());
		for (PermMenu permMenu : permMenus) {
			authorities.add(new SimpleGrantedAuthority(permMenu.getCode()));
		}
		User user = new User(username, permUser.getPwd(),authorities);
		return user;
	}

}
